''' Shared functions and attributes for DocIndexer and DocSearcher
    classes.
'''

import string, os, PyLucene, parsers
from common import EDocIndexer, Doc, Log, relpath

class AbstractIndexer(object):

    INDEX_DIR = '.docindexer'     # Name of directory containing index files.
    OLD_INDEX_DIR = '_docindex_'  # Deprecated pre 0.9.0.1 index directory name.
    MAX_FIELD_LENGTH = 200000
    LISTING_FORMAT = '%(status)-2d%(size)11d%(mtime)21s  %(pathname)s'

    parsers = parsers.Parsers()
    analyzer = PyLucene.StandardAnalyzer()

    def __init__(self):
        self.docsdir = None
        self.format = None

    def indexdir(self, docsdir=None):
        ''' Return the name of the directory in the documents directory
            (docsdir) that will contain the document indexes.
            If the directory does not exist and an old directory exists
            then return the old directory name.
        '''
        __pychecker__ = 'no-shadowbuiltin'
        if docsdir is None:
            docsdir = self.docsdir
        dir = os.path.normpath(os.path.join(docsdir, self.INDEX_DIR))
        if os.path.isdir(dir):
            return dir
        old_dir = os.path.normpath(os.path.join(docsdir, self.OLD_INDEX_DIR))
        if os.path.isdir(old_dir):
            return old_dir
        else:
            return dir


    def check_index_exists(self):
        ''' Throw error if index is missing or obsolete index format is
            detected.
        '''
        msg = ''
        if not os.path.isdir(self.indexdir()):
            msg = 'document index not found'
        elif os.path.isfile(os.path.join(self.indexdir(),'segments')):
            msg = 'obsolete index format'   # Old Lupy index.
        elif not os.path.isfile(os.path.join(self.indexdir(),'segments.gen')):
            msg = 'missing document index files'
        if msg:
            raise EDocIndexer,'%s: rebuild the document index' % msg

    def fspath(self,indexfile):
        ''' Convert a index file path to an absolute file filesystem path.'''
        assert isinstance(indexfile, unicode)
        return os.path.normpath(os.path.join(self.docsdir,indexfile))

    def indexpath(self,fsfile):
        ''' Convert a file filesystem path to an index file path.
            If the file is outside the index documents directory the absolute
            file system path is returned.
        '''
        f = relpath(self.docsdir, fsfile)
        # Convert platform specific to 'normalized' relative path.
        if not os.path.isabs(f):
            f = string.replace(f,os.sep,'/')
        return f

    def docs_gen(self,reader):
        ''' Index document generator.
            Deleted document index entries are skipped.
        '''
        for i in range(reader.maxDoc()):
            if not reader.isDeleted(i):
                yield Doc(reader.document(i),i)



